﻿using Common;
using Common.EnumEntity;
using Microsoft.AspNetCore.Mvc;
using Models.Entity;
using SqlSugar;
using System.Reflection;

namespace ApiService.Utility.InitDatabaseExt
{
    /// <summary>
    /// 是否初始化数据库
    /// </summary>
    public static class InitDatabaseExt
    {
        /// <summary>
        /// 系统初始化
        /// 1.初始化数据库
        /// 2.初始化数据库的管理员用户
        /// </summary>
        /// <param name="builder"></param>
        public static void SystemInit(this WebApplicationBuilder builder)
        {
            SysInitConfig initConfig = new SysInitConfig();
            builder.Configuration.Bind("SysInitConfig", initConfig);
            if (initConfig == null || initConfig.IsInitDatabase == false)
            {
                return;
            }

            ConnectionConfig connection = new ConnectionConfig()
            {
                DbType = DbType.Sqlite,
                IsAutoCloseConnection = true,
                ConnectionString = @"DataSource=D:\data.db3"
            };
            using (SqlSugarClient client = new SqlSugarClient(connection))
            {
                client.DbMaintenance.CreateDatabase();
               


                Assembly assembly = Assembly.LoadFile(Path.Combine(AppContext.BaseDirectory, "Models.dll"));
                Type[] typeArray = assembly.GetTypes()
                    .Where(t => !t.Name.Equals("Sys_BaseModel") && t.Namespace.Equals("Models.Entity"))
                    .ToArray();

                client.CodeFirst.InitTables(typeArray);
               

                #region 初始化管理员身份信息
                //初始化管理员相关信息和权限
                string? adminName = initConfig?.Admin?.AdminName;
                string? adminPass = initConfig?.Admin?.AdminPass;
                if (string.IsNullOrWhiteSpace(adminName) || string.IsNullOrWhiteSpace(adminPass))
                {
                    throw new Exception("初始化系统，请配置管理员信息");
                }
                adminPass = MD5Encrypt.Encrypt(adminPass);
                int inItadministratorsid = 0;
                Sys_User _User = client.Queryable<Sys_User>()
                    .Where(u => !string.IsNullOrWhiteSpace(u.Name) && u.Name.Equals(adminName))
                    .First();

                if (_User != null)
                {
                    inItadministratorsid = _User.UserId;
                }
                else
                {
                    inItadministratorsid = client.Insertable<Sys_User>(new Sys_User()
                    {
                        Name = adminName,
                        Password = adminPass,
                        UserType = (int)UserTypeEnum.Administrator,
                        CreateTime = DateTime.Now,
                        Sex = 1,
                        Status = (int)StatusEnum.Normal,
                        QQ = "1234567",
                        Imageurl = "FileUpload/NoImg.jpg"
                    }).ExecuteReturnIdentity();
                }
                #endregion

              
            }
        }

    }

    /// <summary>
    /// 系统初始化需要的配置文件信息
    /// </summary>
    public class SysInitConfig
    {
        /// <summary>
        /// 是否初始化数据库
        /// </summary>
        public bool? IsInitDatabase { get; set; }

        /// <summary>
        /// 管理员
        /// </summary>
        public SysInitUser? Admin { get; set; }
    }

    /// <summary>
    /// 初始化专用的管理员信息
    /// </summary>
    public class SysInitUser
    {
        /// <summary>
        /// 管理员名称
        /// </summary>
        public string? AdminName { get; set; }
        /// <summary>
        /// 管理员密码
        /// </summary>
        public string? AdminPass { get; set; }
    }
}
